from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin

from apps.models import HouseKeeping
from apps.serializers.ListHousekeeping import ListThingSerializer
from apps.serializers.CreateHouseKeeping import HouseKeepingSerializer
from apps.utils.common_mixin import APIListModelMixin, APICreateModelMixin, APIUpdateModelMixin
from apps.utils.common_response import APIResponse
from apps.views.main.user import make_login_log


class AdminThingListView(GenericViewSet):
    def list(self, request):
        keyword = request.GET.get("keyword", None)
        if keyword:
            HouseKeeping_data = HouseKeeping.objects.filter(title__contains=keyword).order_by(
                '-create_time')
        else:
            HouseKeeping_data = HouseKeeping.objects.all().filter().order_by('-create_time')
        serializer = ListThingSerializer(HouseKeeping_data, many=True)
        return APIResponse(msg='查询成功', data=serializer.data)


class AdminThingCreateView(GenericViewSet, APICreateModelMixin):
    queryset = HouseKeeping.objects.all()
    serializer_class = ListThingSerializer


# 更新
class AdminThingUpdateView(GenericViewSet):
    # queryset = HouseKeeping.objects.all()
    # serializer_class = ListThingSerializer
    def create(self, request):
        try:
            id = request.GET.get('id')
            # 编辑更新
            # HouseKeeping_data=HouseKeeping.objects.get(pk=id)
            HouseKeeping_data = HouseKeeping.objects.filter(id=id).first()
        except HouseKeeping.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        serializer = ListThingSerializer(HouseKeeping_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return APIResponse(code=0, msg='更新成功', data=serializer.data)


class AdminThingDeleteView(GenericViewSet):
    # POST请求
    def create(self, request):
        try:
            ids = request.GET.get('ids')
            if ids is None or ids == '':
                return APIResponse(code=1, msg='缺少必要的ids参数')
            ids_arr = ids.split(',')
            res=HouseKeeping.objects.filter(id__in=ids_arr).delete()
        except HouseKeeping.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        return APIResponse(code=0, msg='删除成功')

